#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>

void Usage(std::string proc)
{
    std::cout << "Usage: " << proc << " serverip" << " serverport" << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    // 获取ip，port
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 1. 创建套接字
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        return 2;
    }

    // 2. 构建目标主机信息
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    // tcp client 要bind，不要显示的bind. 第一次send OS会bind
    // 3. 请求连接，只有请求连接成功，才能开始发送信息，和接受信息
    int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        std::cerr << "connect error" << std::endl;
        return 3;
    }

    // 接下来，连接成功，可以输入开始发送信息了，接受信息
    while (true)
    {
        std::cout << "Please Enter# ";
        std::string outstring;
        std::getline(std::cin, outstring);
        ssize_t s = send(sockfd, outstring.c_str(), outstring.size(), 0); // write
        if (s > 0)
        {
            char inbuffer[1024];
            ssize_t m = recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0); // read
            if (m > 0)
            {
                std::cout << inbuffer << std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
    shutdown(sockfd, SHUT_WR);
    //::close(sockfd);
    return 0;
}